#!/bin/sh

set -ex
cd $(dirname $0)/..

wordsize=$1
if [ "$wordsize" != "" ]; then
    pacman -Sy --noconfirm make base-devel tar zip unzip
    if [ ! -x /c/msys64/mingw$wordsize/bin/g++.exe ]; then
        if [[ $wordsize == 64 ]]; then
            pacman -Sy --noconfirm mingw-w64-x86_64-toolchain
        else
            pacman -Sy --noconfirm mingw-w64-i686-toolchain
        fi
    fi
    PATH=/c/msys64/mingw$wordsize/bin:$PATH
fi

if g++ -v 2>&1 | grep Target: | grep -q x86_64; then
    wordsize=64
else
    wordsize=32
fi
cwd=`pwd`
rm -rf stage/$wordsize
mkdir -p stage

g++ -v
cl

rm -rf build
mkdir build
cd build

source ../dist/versions
tar xzf ../dist/$jpeg_dist
tar xzf ../dist/$openssl_dist
tar xzf ../dist/$zlib_dist
mkdir perl
cd perl
curl -L $perl_src -o $perl_dist
unzip -q $perl_dist
cd ..
mkdir nasm
cd nasm
unzip -q ../../dist/$nasm_dist
cd ..

cd zlib*
make -j$(nproc) -f win32/Makefile.gcc install \
    BINARY_PATH=$cwd/stage/$wordsize/bin \
    INCLUDE_PATH=$cwd/stage/$wordsize/include \
    LIBRARY_PATH=$cwd/stage/$wordsize/lib
make -f win32/Makefile.gcc clean

rm -f *.lib *.obj
for i in adler32 compress crc32 deflate gzclose gzlib gzread \
       gzwrite infback inffast inflate inftrees trees uncompr zutil; do
    cl -nologo -O2 -Zi -Gy -MD -c $i.c
done
lib -nologo /out:z.lib *.obj
cp z.lib $cwd/stage/$wordsize/lib
cd ..

cd jpeg*

./configure --disable-shared
DESTDIR=$cwd/stage/$wordsize make -j$(nproc) install
if [ -f $cwd/stage/$wordsize/mingw*/lib/jpeg.lib ]; then
    (cd $cwd/stage/$wordsize/mingw*/lib; mv jpeg.lib libjpeg.a);
fi
make distclean

CC=cl CXX="cl -TP -GR" ./configure --disable-shared
make
cp -p .libs/jpeg.lib $cwd/stage/$wordsize/lib
make distclean

cd ..

cd openssl*

OPATH=$PATH
nasm_path=$(echo $cwd/build/nasm/nasm-*)
PATH=$nasm_path:$PATH
nasm -v
if [ "$wordsize" = "64" ]; then
    mingw=mingw64
else
    mingw=mingw
fi
# Note: no-module is required to prevent legacy providers, like rc4
# and md5, from being in a dynamically loaded module.
./Configure $mingw no-shared no-module
make -j$(nproc) install_dev DESTDIR=$cwd/ INSTALLTOP=stage/$wordsize
make distclean

# Strawberry perl doesn't work when building with mingw in the msys
# environment, so use it for the VC build only.
PATH=$cwd/build/perl/perl/bin:$PATH
suf=
if [ "$wordsize" = "64" ]; then
    suf=A
fi
./Configure VC-WIN${wordsize}${suf} no-shared no-module
nmake install_dev INSTALLTOP=$cwd/stage/$wordsize
PATH=$OPATH

cd ..
